package org.ting.book.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.ting.book.component.ResultFail;
import org.ting.book.component.ResultGenerator;
import org.ting.book.component.ResultSuccess;
import org.ting.book.mapper.BookMapper;
import org.ting.book.model.BookInfo;
import org.ting.book.model.Result;

import java.util.List;

@Service
public class BookService {
    @Autowired
    BookMapper bookMapper;
    ResultGenerator success = new ResultSuccess();
    ResultGenerator fail = new ResultFail();
    public List<BookInfo> getBookList() {
        //todo 接口回调
        return bookMapper.getBookList();
    }
    public Result<?> insertBook(BookInfo book) {
        if(bookMapper.insertBook(book) == 1) {
            return success.getResult();
        }
        return fail.getResult();
    }
    public BookInfo getBookById(Integer bookId) {
        return bookMapper.getBookById(bookId);
    }
    public Result<?> deleteBookById(Integer id) {
        BookInfo bookInfo = bookMapper.getBookById(id);
        if(!bookInfo.getCount().equals(bookInfo.getTotal())) {
            return fail.getResult("该书存在外借，无法删除");
        }
        if(bookMapper.deleteBookById(id) == 1) {
            return success.getResult();
        }
        return fail.getResult();
    }
    public Result<?> updateBook(BookInfo book) {
        BookInfo old = bookMapper.getBookById(book.getId());
        //计算更新后的total
        book.setTotal(old.getTotal() + book.getCount() - old.getCount());
        if(bookMapper.updateBook(book) == 1) {
            return success.getResult();
        }
        return fail.getResult();
    }
}
